package com.sky.controller.common;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * 公用 上传文件类
 */
@Api(tags = "公用请求接口")
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        /* 获取原始文件名 */
        String originalFilename = file.getOriginalFilename();
        log.info("文件上传：{}", originalFilename);
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = null;
        try {
            String FileName = UUID.randomUUID().toString() + substring;
            /* 使用 AliOssUtil 调用 upload方法进行上传文件 */
            url = aliOssUtil.upload(file.getBytes(), FileName);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
            return Result.error("文件上传失败");
        }
        return Result.success(url);
    }

}
